package com.seupyy.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.seupyy.mapper.ArticleMapper;
import com.seupyy.pojo.PageBean;
import com.seupyy.service.ArticleService;
import com.seupyy.pojo.Article;
import com.seupyy.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public void add(Article article) {
        //补充参数
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());

        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        article.setCreateUser(id);

        articleMapper.add(article);
    }

    @Override
    public PageBean<Article> list(Integer pageNum, Integer pageSize, Integer categoryId, String state) {
        //构建PageBean对象
        PageBean<Article> pb = new PageBean<>();

        //开启分页查询
        PageHelper.startPage(pageNum, pageSize);

        //调用mapper完成查询
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer uid = (Integer) map.get("id");
        List<Article> querylist = articleMapper.list(categoryId, state, uid);
        //Page中提供了方法，可以获取PageHelper分页查询后的总记录数和当前页数据
        Page<Article> convertlist = (Page<Article>) querylist;

        //把数据填充到PageBean对象中
        pb.setTotal(convertlist.getTotal());
        pb.setItems(convertlist.getResult());
        return pb;
    }
}
